/*
 *	create by senllang 2023/5/3
 *  mail : study@senllang.onaliyun.com
 *	
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include "process.h"

/* 进程类型 */
int processType = 0;

/*
 * 等待子进程结束，或者处理僵尸进程
 *
 * create by senllang 2023/5/2
 *
 */
void WaitSubProcessComplete(void)
{
    int status;
    int ret = 0;

	while(1)
	{
		ret = waitpid(-1, &status, 0);
		if(ret < 0)
		{
			if(errno == EINTR)
				continue;
			if(errno == ECHILD)
				break;
		}
		
		/* subprocess exited . */
		printf("subprocess [%d] exited. \n", ret);
	}

	printf("all subprocess eixted .\n");
}


/*
 * 创建多个子进程
 *
 * 返回值为成功创建子进程的个数
 *
 * create by senllang 2023/5/2
 *
 * Num, 需要创建子进程的个数
 * argc,argv, 传给子进程任务主函数的参数
 *
 */
int CreateSubProcess(int Num, int argc, char *argv[])
{
	int pid = 0;
	int i = 0;
	
	for(i = 0; i < Num; i++)
	{
		/* 定义两个写进程 */
		if(i <= 0)
			processType = 1;
		else
			processType = 0;

		pid = fork();
		if(0 == pid)
		{
			exit(ProcessMain(argc, argv));
		}
		else if(pid < 0)
		{
			printf("fork subprocess error.[%s]\n",strerror(errno));
			break;
		}
		
		/* In parent, continue to creating process on. */
	}
	
	return i;
}
